#include "as2_t1.h"

#include <stdio.h>

unsigned char bitAt[] = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80 };
unsigned char memSlots[MEM_BLOCK_SIZE/8];

void *task_alloc() {
	int blockIx = 0;
	task_t* result;
	while ((memSlots[blockIx/8] & bitAt[blockIx%8]) && blockIx < MAX_TASK_COUNT) {
		blockIx++;
	}
	if (blockIx == MAX_TASK_COUNT - 1) {
		return NULL;
	}
	/* // zet slot op bezet */
	memSlots[blockIx/8] = memSlots[blockIx/8] | bitAt[blockIx%8];
	result = (task_t*)get_MEM_BLOCK_START();
	/* // printf("alloc mem: %p, ix: %8d\n", (void*)&result[blockIx], blockIx); */
	return (void*)&result[blockIx];
	/* // return (void*)((int)get_MEM_BLOCK_START() + (int)blockIx * sizeof(task_t)); */
}

void task_free(void *ptr) {
	/* // bereken de index relatief tot het begin van het geheugen */
	int blockIx;
	blockIx = ((int)(ptr) - (int)(get_MEM_BLOCK_START())) / sizeof(task_t);
	/* // controleer of de blockIx valt binnen het toegestane geheugen */
	if (blockIx >= 0 && blockIx < MAX_TASK_COUNT) {
		/* // zet slot op open */
		memSlots[blockIx/8] = memSlots[blockIx/8] & ~bitAt[blockIx%8];
		/* // printf("freed mem: %p, ix: %8d\n", ptr, blockIx); */
	}
}

